import {
	token,
	tokenName,
	axiosTimeout,
	axiosChannelHeader,
	axiosSuccessCode,
	axiosRefreshCode,
	refreshTokenName,
} from "/config"

import Axios from "axios"
import { useUserInfoStore } from "/store/userInfo"

import refreshToken from "./refreshToken"
import { downloadFileStream } from "/plugins/file"

Axios.defaults.baseURL = ""
Axios.defaults.timeout = axiosTimeout

Axios.interceptors.request.use(
	config => {
		const url = config.url || ""
		if (!/^http/.test(url)) {
			if (!axiosChannelHeader.some(item => url.startsWith(item))) {
				const channel = config.channel || "api"
				config.url = `/${channel}` + url
			}
		}

		if (!config.headers) {
			config.headers = {}
		}
		// config.headers[tokenName] = token()
		if (url == `/refreshToken`) {
			config.headers["token"] = token()
		} else {
			config.headers[tokenName] = token()
		}
		if (config.data instanceof FormData) {
			return config
		}

		if (config.method === "get" || config.method === "delete") {
			config.params = {
				...config.params,
			}
		} else {
			if (!Array.isArray(config.data)) {
				config.data = {
					...config.data,
				}
			}
		}
		return config
	},
	e => {
		return Promise.reject(e || "接口报错")
	}
)

Axios.interceptors.response.use(
	async result => {
		if (Array.isArray(result) || (!result.request && !result.headers && !result.config)) {
			return result
		}
		if (result.data == undefined || result.data == null || result.status !== 200) {
			return Promise.reject(result || "接口报错")
		}
		if (result.config.download) {
			let filename = result.headers["content-disposition"]
			let extension = ""
			if (filename != void 0 && filename.lastIndexOf(".") > 0) {
				let parts = filename.split(".")
				extension = parts[parts.length - 1]
			}
			downloadFileStream(
				result.data,
				result.config.download.type == null ? extension : result.config.download.type,
				result.config.download.type == null
					? result.config.download.filename + "." + extension
					: result.config.download.filename
			)
			// downloadFileStream(result.data, result.config.download.type, result.config.download.filename)
			return result.data
		} else if (result.config.blob) {
			return result.data
		} else {
			if ([1001].includes(result.data.code)) {
				const userInfoStore = useUserInfoStore()
				userInfoStore.logout()
				return Promise.reject(result.data.msg || "接口报错")
			}
			if (result.data.code == axiosRefreshCode) {
				try {
					await refreshToken()
					return Axios.request(result.config)
				} catch (error) {
					return Promise.reject(error.msg || error.data || "接口报错")
				}
			}
			if (result.data.code !== axiosSuccessCode) {
				console.error("接口报错: ", result)
				return Promise.reject(result.data.msg || "接口报错")
			}

			return typeof result.data.data !== "undefined" ? result.data.data : result.data
		}
	},
	error => {
		console.log(error)
		return Promise.reject("接口报错")
	}
)

const http = {
	get(url, params, configOptions = {}) {
		let config = {}
		if (typeof params === "string" || typeof params === "number") {
			url += "/" + params
		} else if (typeof params !== "undefined") {
			config = { params }
		}
		if (configOptions.download || configOptions.blob) {
			configOptions.responseType = "blob"
		}
		return Axios.get(url, { ...config, ...configOptions })
	},
	post(url, data, configOptions = {}) {
		if (configOptions.download || configOptions.blob) {
			configOptions.responseType = "blob"
		}
		return Axios.post(url, data, configOptions)
	},
	put(url, data, configOptions = {}) {
		return Axios.put(url, data, configOptions)
	},
	delete(url, params, configOptions = {}) {
		let config = {}
		if (typeof params === "string" || typeof params === "number") {
			url += "/" + params
		} else if (typeof params !== "undefined") {
			config = { params }
		}
		return Axios.delete(url, { ...config, ...configOptions })
	},
}

export default {
	install: app => {
		app.config.globalProperties.$axios = http
	},
}

export const getAxios = http.get
export const postAxios = http.post
export const putAxios = http.put
export const deleteAxios = http.delete
